package da.metricscraft.client.threads;

import java.io.IOException;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.xml.sax.SAXException;

import da.metricscraft.client.frames.LoadingPanel;

public abstract class XMLLoader<T> extends Thread {
	private LoaderTypes type;
	protected T data;
	protected Document xmldoc;
	protected String path = "";
	private LoadingPanel listener;
	private static XMLLoader<?> singleton;
	public XMLLoader(LoaderTypes type){
		this.type = type;
		singleton = this;
	}
	public static XMLLoader<?> getInstance(){
		if (singleton == null){
			System.err.println("Error getting singleton: XMLLoader");
		}
		return singleton;
	}
	public enum LoaderTypes{
		SPATIAL,
		BIOMS, 
		PLAYER
	}
	@Override
	public abstract void run();
	public final Document getXml(){
		return xmldoc;
	}
	public final void releaseXml(){
		xmldoc = null;
	}
	public final T getData(){
		return data;
	}
	public synchronized final void load(String path){
		this.path = path;
		this.notifyAll();
	}
	public LoaderTypes getType(){ 
		return type; 
	}
	public void addFinishListener(LoadingPanel f){
		listener = f;
	}
	protected void dispatch(){
		listener.finishedLoading(this);
	}
	protected void readXML(){
		boolean worked = true;
		do{
			try {
				xmldoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(path);
			} catch (SAXException e) {
				worked = false;
				e.printStackTrace();
			} catch (IOException e) {
				worked = false;
				e.printStackTrace();
			} catch (ParserConfigurationException e) {
				worked = false;
				e.printStackTrace();
			}

		}while (!worked);
	}
}